import { acceptHMRUpdate, defineStore } from 'pinia'
import { store } from '../index'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { decodeAES, encodeAES } from '@/utils/aesRsa'
import type { UserType } from '@/api/auth/types'

export const useUserStore = defineStore('user', () => {
  const { wsLocal } = useCache()
  const userInfo = ref<UserType>(null)

  const getUserInfoCache = () => {
    if (wsLocal.getItem(CACHE_KEY.SYSTEM_USER_INFO)) {
      userInfo.value = decodeAES(wsLocal.getItem(CACHE_KEY.SYSTEM_USER_INFO))
    }
  }

  const setUserInfoCache = () => {
    wsLocal.setItem(CACHE_KEY.SYSTEM_USER_INFO, encodeAES(userInfo.value))
  }

  const removeUserInfoCache = () => {
    wsLocal.removeItem(CACHE_KEY.SYSTEM_USER_INFO)
    setTimeout(() => {
      userInfo.value = null
    }, 100)
  }

  return {
    userInfo,
    getUserInfoCache,
    setUserInfoCache,
    removeUserInfoCache
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
}

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
